package com.qf.smsplatform.webmaster.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.webmaster.dao.TChannelMapper;
import com.qf.smsplatform.webmaster.dao.TClientBusinessMapper;
import com.qf.smsplatform.webmaster.dao.TClientChannelMapper;
import com.qf.smsplatform.webmaster.dto.DataGridResult;
import com.qf.smsplatform.webmaster.dto.QueryDTO;
import com.qf.smsplatform.webmaster.pojo.*;
import com.qf.smsplatform.webmaster.service.ClientChannelService;
import com.qf.smsplatform.webmaster.service.api.CacheService;
import com.qf.smsplatform.webmaster.util.JsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ClientChannelServiceImpl implements ClientChannelService {

    @Resource
    private TClientChannelMapper tClientChannelMapper;
    @Resource
    private TClientBusinessMapper tClientBusinessMapper;

    @Resource
    private TChannelMapper tChannelMapper;

    @Resource
    private CacheService cacheService;

    @Override
    public int addClientChannel(TClientChannel tClientChannel) {
        int i =  tClientChannelMapper.insertSelective(tClientChannel);
        Map<String, String> stringObjectMap = JsonUtils.objectToMap(tClientChannel);
        cacheService.hMSet("ROUTER:"+tClientChannel.getClientid(),stringObjectMap);
        return i;
    }

    @Override
    public int delClientChannel(Long id) {
        TClientChannel tClientChannel = findById(id);
        cacheService.del("ROUTER:"+tClientChannel.getClientid());
        return tClientChannelMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateClientChannel(TClientChannel tClientChannel) {
        int i = tClientChannelMapper.updateByPrimaryKey(tClientChannel);
        if (i > 0) {
//            tClientChannel.setCorpname("");
//            tClientChannel.setChannelname("");
            Map stringObjectMap = JsonUtils.objectToMap(tClientChannel);
            cacheService.hMSet("ROUTER:" + tClientChannel.getClientid(), stringObjectMap);
        }
        return i;
    }

    @Override
    public TClientChannel findById(Long id) {
        return tClientChannelMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TClientChannel> findAll() {
        return tClientChannelMapper.selectByExample(null);
    }

    @Override
    public DataGridResult findByPage(QueryDTO queryDTO) {
        PageHelper.offsetPage(queryDTO.getOffset(), queryDTO.getLimit());
        TClientChannelExample example = new TClientChannelExample();
        String sort = queryDTO.getSort();
        if (!StringUtils.isEmpty(sort)) {
            example.setOrderByClause("id");
        }
        List<TClientChannel> tClientChannels = tClientChannelMapper.selectByExample(example);
        for (TClientChannel tClientChannel : tClientChannels) {
            Long clientid = tClientChannel.getClientid();
            TClientBusiness tClientBusiness = tClientBusinessMapper.selectByPrimaryKey(clientid);
            String corpname = tClientBusiness.getCorpname();
            tClientChannel.setCorpname(corpname);
            long channelid = (long)tClientChannel.getChannelid();
            TChannel tChannel = tChannelMapper.selectByPrimaryKey(channelid);
            String channelname = tChannel.getChannelname();
            tClientChannel.setChannelname(channelname);
        }
        PageInfo<TClientChannel> info = new PageInfo<>(tClientChannels);
        long total = info.getTotal();
        DataGridResult result = new DataGridResult(total, tClientChannels);
        return result;
    }

    @Override
    public void sync() {
        // 将CHANNEL:作为前缀，后缀添加上ClientID    作为key
        // value使用set结构，存储当前客户绑定的多个通道信息（clientID,channelId,spNumber,extendNumber,fee,channelType）
        List<ClientChannelStrategy> list = tClientChannelMapper.findClientChannel();
        // 将上述的内容在当前方法中查询并封装好,存储到Redis中
        // key -> ClientID    value = ClientChannelStrategy对象
        Map<String, Set<ClientChannelStrategy>> data = new HashMap();
        for (ClientChannelStrategy clientChannelStrategy : list) {
            Set<ClientChannelStrategy> set = data.get(clientChannelStrategy.getClientID() + "");
            if(set == null){
                // 没有给set设置数据
                set = new HashSet<>();
                set.add(clientChannelStrategy);
                data.put(clientChannelStrategy.getClientID() + "",set);
            }else{
                // 当前clientID中已经有对应的ClientChannelStrategy对象的数据
                set.add(clientChannelStrategy);
            }
        }
        // 将封装好的数据保存到Redis中
        for (Map.Entry<String, Set<ClientChannelStrategy>> entry : data.entrySet()) {
            // 准备存到Redis的key
            String key = CacheConstants.CACHE_PREFIX_SMS_CHANNEL + entry.getKey();
            // 准备存到Redis的value
            Set<ClientChannelStrategy> clientChannelSet = entry.getValue();
            // 调用cache模块存储
            cacheService.saddObject(key,clientChannelSet.toArray());
        }

    }


}
